Skip to main content
  1. SwiftUI in 100 Days Notes/

Day 6 - Swift Loops

Computers are very good at performing repetitive operations. In Swift, these repetitive structures are called loops. There are two loops used in Swift; for and while loops.

for Loop #

Suppose we have a String Array. To print each element of this Array one by one to the terminal, we can write a code like below.

let platforms = ["iOS", "macOS", "tvOS", "watchOS"]

for os in platforms {
    print("Swift works great on \(os).")
}

//OUTPUT:
//----------------------------------------
// Swift works great on iOS.
// Swift works great on macOS.
// Swift works great on tvOS.
// Swift works great on watchOS.

This loops over the platform Array, placing each item one by one into os. We have not created the os variable elsewhere, it is part of the loop and can only be used inside the loop brackets.

The code we want to run for each item in the Array is written in { } brackets. Therefore, four lines of text are written on the screen.

The general naming used in loops is as follows.

  • Loop Body : It is the code inside the { } brackets.
  • Loop Iteration : It is 1 cycle made during the loop.
  • Loop Variable : It exists throughout the loop body and changes its value at each loop iteration.

Instead of an Array (or Set, or Dictionary), we can also loop through a fixed range of numbers.

for i in 1...12 {
    print("5 x \(i) is \(5 * i)")
}

//OUTPUT:
//----------------------------------------
// 5 x 1 is 5
// 5 x 2 is 10
// 5 x 3 is 15
// 5 x 4 is 20
// 5 x 5 is 25
// 5 x 6 is 30
// 5 x 7 is 35
// 5 x 8 is 40
// 5 x 9 is 45
// 5 x 10 is 50
// 5 x 11 is 55
// 5 x 12 is 60

There are some things we should mention at this point;

  • A common convention in fixed range loops is to use i as the loop variable. If we have a second number we use j and for a third number we use k. If we have a fourth number we should choose a better naming 😊
  • The 1...12 part is called range. It means; “All integers between 1 and 12, including 1 and 12.” Range is a Swift-specific data type.
for i in 1...12 {
    print("The \(i) times table:")

    for j in 1...12 {
        print("  \(j) x \(i) is \(j * i)")
    }

    print()
}

//OUTPUT:
//----------------------------------------
//The 1 times table:
//  1 x 1 is 1
//  2 x 1 is 2
//  3 x 1 is 3
//  4 x 1 is 4
//  5 x 1 is 5
//  6 x 1 is 6
//  7 x 1 is 7
//  8 x 1 is 8
//  9 x 1 is 9
//  10 x 1 is 10
//  11 x 1 is 11
//  12 x 1 is 12

//The 2 times table:
//.
//.
//.
//This output is quite long, you'd better try it in your own Xcode Playground.

Here we have a nested loop. We count from 1 to 12 and count each number inside it again from 1 to 12.

Swift Range (x…y) #

When you see x…y you know it creates a range that starts at whatever number x is, and counts up to and including whatever number y is.

Swift has another Range that counts to the last number but excludes the last number. ..<5

for i in 1...5 {
    print("Counting from 1 through 5: \(i)")
}

print()

for i in 1..<5 {
    print("Counting 1 up to 5: \(i)")
}

//OUTPUT:
//----------------------------------------
// Counting from 1 through 5: 1
// Counting from 1 through 5: 2
// Counting from 1 through 5: 3
// Counting from 1 through 5: 4
// Counting from 1 through 5: 5

// Counting 1 up to 5: 1
// Counting 1 up to 5: 2
// Counting 1 up to 5: 3
// Counting 1 up to 5: 4

Sometimes, we may want to create a loop using a Range and not use the loop variable. In such a case, we use _ instead of the loop variable.

var lyric = "Haters gonna"

for _ in 1...5 {
    lyric += " hate"
}

print(lyric)

//OUTPUT:
//----------------------------------------
//Haters gonna hate hate hate hate hate

while Döngüsü #

Swift has another loop called while. The while loop will continue to run until the condition it checks is false.

Here is an example of a while loop;

var countdown = 10

while countdown > 0 {
    print("\(countdown)…")
    countdown -= 1
}

print("Blast off!")

//OUTPUT:
//----------------------------------------
// 10…
// 9…
// 8…
// 7…
// 6…
// 5…
// 4…
// 3…
// 2…
// 1…
// Blast off!

The while loop is very useful when we don’t know how long the loop will run.

Both Int and Double have a function called random(in:). This function generates a random number within a given range.

To generate random numbers between 1 and 1000;

let id = Int.random(in: 1...1000)

To generate a random number between 0 and 1;

let amount = Double.random(in: 0...1)

Using a while loop and the function random(in:) we can make a 20-sided dice rolling game.

The loop will only terminate when 20 comes up.

// create an integer to store our roll
var roll = 0

// carry on looping until we reach 20
while roll != 20 {
    // roll a new dice and print what it was
    roll = Int.random(in: 1...20)
    print("I rolled a \(roll)")
}

// if we're here it means the loop ended – we got a 20!    
print("Critical hit!")

for loops are useful when we have limited data, like a range or an Array. while loops are useful when we need a special condition.

break and continue #

Swift gives us two ways to skip one or more elements in a loop: continue allows us to skip the currently executing iteration of the loop, and break allows us to skip all remaining iterations of the loop.

continue #

For example, let’s say we want to print the file name with extension “.jpg” from an Array to the terminal;

let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == false {
        continue
    }

    print("Found picture: \(filename)")
}

//OUTPUT:
//----------------------------------------
// Found picture: me.jpg
// Found picture: sophie.jpg

A String Array is created. Each String is then taken and checked to see if it has the “.jpg” extension. continue is activated for each String that does not have the “.jpg” extension, skipping the loop iteration.

break #

break exits the loop immediately and skips all remaining iterations. Let’s analyze the following example;

let number1 = 4
let number2 = 14
var multiples = [Int]()

for i in 1...100_000 {
    if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
        multiples.append(i)

        if multiples.count == 10 {
            break
        }
    }
}

print(multiples)
//OUTPUT:
//----------------------------------------
// [28, 56, 84, 112, 140, 168, 196, 224, 252, 280]

Let’s analyze what is done in this example;

  1. Create two constants to hold two numbers.
  2. Create an Array to hold the common multiple of the two numbers.
  3. Count from 1 to 100,000, assigning a value to the loop variable i.
  4. If i is a multiple of both the first and second number, it is added to the multiplies Array.
  5. When 10 common multiples are reached, break is used to exit the loop.
  6. The multiplies Array is printed to the terminal screen.

Swift Labeled Statements #

In Swift, labeled expressions allow us to name specific parts of our code and are often used to exit nested loops.

Suppose we have a locked safe. This safe can be unlocked with a certain combination.

Here are the options we can do;

let options = ["up", "down", "left", "right"]

The secret combination of the safe is this;

let secretCombination = ["up", "up", "right"]

Let’s try to find the combination of this safe with the available movement options;

outerLoop: for option1 in options {
    for option2 in options {
        for option3 in options {
            print("In loop")
            let attempt = [option1, option2, option3]

            if attempt == secretCombination {
                print("The combination is \(attempt)!")
                break outerLoop
            }
        }
    }
}
//OUTPUT:
//----------------------------------------
// In loop
// In loop
// In loop
// In loop
// The combination is ["up", "up", "right"]!

If we had not used the outerloop label and break in the code above, the loops would have continued to run despite finding the hidden combination.

Even if we used break but not the outerloop label, we would exit loop3 but remain in the other two loops.

Using outlerloop and break together, we tell Swift: “Exit all loops as soon as the hidden combination is found.”

You can also read this article in Turkish.
Bu yazıyı Türkçe olarak da okuyabilirsiniz.

This article contains the notes I took for myself from the articles found at SwiftUI Day 6. Please use the link to follow the original lesson.